package com.jianzong.lingxuan.im;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @auth Leiwenlong
 * @since 2021/1/30
 *   自定义Handlder
 */
public class MyChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    //用来保存所有客户端连接
    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private SimpleDateFormat sdf =new SimpleDateFormat("YYYY-MM-dd HH:mm");

    //当通道（channel）内有新的消息会自动调用
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        //获取客户端发送过来的文本消息
        String text = msg.text();
        System.out.println("接收到的消息:"+text);

        String[] split = text.split("\\*&");

        for(Channel channel : clients){
            String asLongText = channel.id().asLongText().substring(0,6);
            channel.writeAndFlush(new TextWebSocketFrame(asLongText+"*&"+sdf.format(new Date())+"*&"+split[0]
                    +"*&"+split[1]+"*&"+split[2]
            ));
        }
    }

    //当有新的客户端连接服务器后 会自动调用这个方法
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel());
    }
}
